package com.songcha.module_bookshelf.ui.fragment.bookshelf

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_base.mvvm.base.BaseRefreshMvvmFragment
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.enums.BookDownloadStatus
import com.songcha.library_business.event.book.BookDownloadCompleteEvent
import com.songcha.library_business.event.book.BookDownloadErrorEvent
import com.songcha.library_business.event.book.BookDownloadingEvent
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.AdvertHelper.INativeExpressAdListener
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.proxy.main.MainEventProxy
import com.songcha.library_business.proxy.personal_recommend.PersonalRecommendManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.module_bookshelf.R
import com.songcha.module_bookshelf.databinding.BookshelfFragmentBookshelfBinding
import com.songcha.module_bookshelf.structs.BookShelfItem
import com.songcha.module_bookshelf.ui.adapter.BookShelfAdapter
import com.songcha.module_bookshelf.ui.decoration.BookShelfItemDecoration
import me.jessyan.autosize.AutoSizeConfig
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path="/bookshelf/BookShelfFragment")
class BookShelfFragment : BaseRefreshMvvmFragment<BookShelfViewModel, BookshelfFragmentBookshelfBinding>(),
    View.OnClickListener,
    BookShelfAdapter.IOnBookShelfItemCheckListener,
    BottomNavigationView.IOnBottomNavigationItemChangeListener,
    OnItemClickListener
{

    init {
        TAG=BookShelfFragment::class.java.simpleName
    }

    private var mAdapter:BookShelfAdapter<BookshelfFragmentBookshelfBinding>?=null

    override fun getLayoutId(): Int {
        return R.layout.bookshelf_fragment_bookshelf
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        databinding.bookshelfTvBrowseHistory.setOnClickListener(this)
        databinding.bookshelfTvManage.setOnClickListener(this)
        databinding.bookshelfCclDel.setOnClickListener(this)
        databinding.bookshelfTvSelectAll.setOnClickListener(this)
        databinding.bookshelfIvNodata.setOnClickListener(this)
        databinding.bookshelfClTodayRecommend.setOnClickListener(this)

        //getData()

        EventBus.getDefault().register(this)

    }

    private fun loadBannerAdvert(){
        //TODO
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_BANNER,VarConfig.ADVERT_BOOK_SHELF_BANNER_INFO,
            databinding.bookshelfFlAdvertBanner,0f,object :AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    ViewHelper.setVisibility(true,databinding.bookshelfFlAdvertBanner)
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        databinding.bookshelfFlAdvertBanner.removeAllViews()
                        databinding.bookshelfFlAdvertBanner.addView(view)
                    }else{

                    }
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    databinding.bookshelfFlAdvertBanner.removeAllViews()
                    ViewHelper.setVisibility(false,databinding.bookshelfFlAdvertBanner)
                }

                override fun onClose(type: Int) {
                    databinding.bookshelfFlAdvertBanner.removeAllViews()
                    ViewHelper.setVisibility(false,databinding.bookshelfFlAdvertBanner)
                }

            }
        )

    }

    //cause list siz==0 need show nodata,so override addRlstObserve()
    override fun addRlstObserve() {
        viewModel!!.rlst.observe(this){
            if(it!=null){
                initListData()
            }
        }
    }

    override fun initListData() {
        initRcv(viewModel.rlst.value!!)
    }

    override fun onLoadNoData() {
        super.onLoadNoData()
        databinding.bookshelfTvManage.visibility=View.GONE
        //if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED)
            databinding.bookshelfFlNodata.visibility=View.VISIBLE
    }

    override fun onRefreshNoData() {
        super.onRefreshNoData()
        databinding.bookshelfTvManage.visibility=View.GONE
        //if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED)
            databinding.bookshelfFlNodata.visibility=View.VISIBLE
    }

    override fun onLoadSuccess() {
        super.onLoadSuccess()
        databinding.bookshelfTvManage.visibility=View.VISIBLE
        //if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED)
            databinding.bookshelfFlNodata.visibility=View.GONE
    }

    override fun onRefreshSuccess() {
        super.onRefreshSuccess()
        databinding.bookshelfTvManage.visibility=View.VISIBLE
        //if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED)
            databinding.bookshelfFlNodata.visibility=View.GONE
    }

    override fun getRefreshLayout(): SmartRefreshLayout {
       return databinding.bookshelfSrl
    }

    override fun getListAdapter(): RecyclerView.Adapter<BaseViewHolder>? {
        if(mAdapter==null) return mAdapter
        return mAdapter as RecyclerView.Adapter<BaseViewHolder>
    }


    override fun isInitViewGetData(): Boolean {
        return false
    }

    override fun onGetData() {
        if(!isViewModelInitialized()) return
        if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED && PersonalRecommendManager.getPersonalRecommendEnabled())
            viewModel.getTodayRecommendBook()
        viewModel.getBookShelfList()
        viewModel.getTodayReadTime()

    }


    override fun onResume() {
        super.onResume()
        if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED && PersonalRecommendManager.getPersonalRecommendEnabled()){
            databinding.bookshelfClTodayRecommend.visibility=View.VISIBLE
        }else{
            databinding.bookshelfClTodayRecommend.visibility=View.GONE
        }
        onGetData()

        loadBannerAdvert()
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun initObserver() {
        /* viewModel.shelfList.observe(this){data->
            initRcv(data)
            if(data.size==0){
                databinding.bookshelfTvManage.visibility=View.GONE
            }else{
                databinding.bookshelfTvManage.visibility=View.VISIBLE
            }
        }*/

        viewModel.todayRecommendBookState.observe(this){data->
            if(data){
                databinding.bookshelfClTodayRecommend.visibility=View.VISIBLE
            }else{
                databinding.bookshelfClTodayRecommend.visibility=View.GONE
            }
        }

        viewModel.todayRecommendBook.observe(this){data->
            GlideUtil.loadNetImage(databinding.bookshelfIvRecommendThumb,data.cover)
            databinding.bookshelfTvRecommendBookname.text="《"+data.bookName+"》"
            databinding.bookshelfTvRecommendDesc.text=data.description
        }

        viewModel.todayReadTime.observe(this){data->
            if(data<=0){
                databinding.bookshelfTvDayReadTime.text="今天还没开始阅读"
            }else{
                databinding.bookshelfTvDayReadTime.text="今天已阅读${(data/60)}分钟"
            }
        }

        viewModel.isManage.observe(this){data->
            mAdapter?.setIsManage(data)
            MainEventProxy.postHideBottomNavigationEvent(data)
            if(data){
                databinding.bookshelfTvManage.text="取消"
                databinding.bookshelfCclDel.visibility=View.VISIBLE
                databinding.bookshelfTvSelectAll.visibility=View.VISIBLE
                databinding.bookshelfCclDayReadTime.visibility=View.INVISIBLE
            }else{
                databinding.bookshelfTvManage.text="整理书架"
                databinding.bookshelfCclDel.visibility=View.GONE
                databinding.bookshelfTvSelectAll.visibility=View.GONE
                databinding.bookshelfCclDayReadTime.visibility=View.VISIBLE
            }

        }

        viewModel.isSelectAll.observe(this){data->
            if(data){
                databinding.bookshelfTvSelectAll.text="取消全选"
            }else{
                databinding.bookshelfTvSelectAll.text="全选"
            }
        }
    }

    private fun initRcv(list:MutableList<BookShelfItem>){
        databinding.bookshelfRcv.apply {
            layoutManager=GridLayoutManager(context,3)
            mAdapter=BookShelfAdapter(list,viewModel.isManage.value!!,this@BookShelfFragment,)
            mAdapter!!.setOnItemClickListener(this@BookShelfFragment)
            adapter=mAdapter
            if(itemDecorationCount==0)
                addItemDecoration(BookShelfItemDecoration())
        }
    }

    override fun onBookShelfItemCheck(isCheck: Boolean) {
        viewModel.updateSelectAll()
    }

    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        if(tag==TAG){
            onGetData()
            UMengHelper.onUMEvent(requireContext(),"bottom_tab_shelf")
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if(viewModel.rlst.value==null) return
        val item=viewModel.rlst.value!![position]
        if(viewModel.isManage.value!!){
            mAdapter?.setSelectItem(item,!item.isSelect)
            mAdapter?.notifyDataSetChanged()
            return
        }
        var isFromDownload=item.downloadStatus==BookDownloadStatus.DOWNLOADED
        if(!UserInfoManager.isVip()) isFromDownload=false
        val book=BookBean().apply {
            id=item.bookId
            bookName=item.bookName
            author=item.author
            textCount=item.textCount
            thumb=item.thumb
        }
        BusinessJumpUtil.toBookReader(book,0,isFromDownload)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBookDownloadingEvent(event:BookDownloadingEvent){
        val idx=viewModel.getIndexById(event.book.id)
        if(idx==-1) return
        if(viewModel.rlst.value!![idx].downloadStatus==BookDownloadStatus.DOWNLOADING) return
        viewModel.updateItemDownloadStatus(idx,BookDownloadStatus.DOWNLOADING)
        mAdapter?.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBookDownloadCompleteEvent(event:BookDownloadCompleteEvent){
        val idx=viewModel.getIndexById(event.book.id)
        if(idx==-1) return
        viewModel.updateItemDownloadStatus(idx, BookDownloadStatus.DOWNLOADED)
        mAdapter?.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBookDownloadErrorEvent(event: BookDownloadErrorEvent){

    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.bookshelf_tv_browse_history->{
                ARouter.getInstance().build("/mine/BrowseHistoryActivity").navigation()
            }
            R.id.bookshelf_tv_manage-> {
                if(viewModel.isManage.value!!){
                    viewModel.setIsManage(false)
                }else{
                    viewModel.setIsManage(true)
                }
            }
            R.id.bookshelf_tv_selectAll->{
                if(viewModel.isSelectAll.value!!){
                    //unselect all
                    viewModel.unSelectAll()
                    mAdapter?.notifyDataSetChanged()
                }else{
                    viewModel.selectAll()
                    mAdapter?.notifyDataSetChanged()
                }
            }
            R.id.bookshelf_ccl_del->{
                val ids=viewModel.getCheckIds()
                if(ids.size==0){
                    ToastUtil.show("请选择需要删除的书籍")
                    return
                }
                val db=CustomDialog.Companion.Builder(v.context)
                db.setDialogMsg("您确定移出书架吗？")
                    .setOnConfirmListener {
                        viewModel.delBookShelfByIds(ids)
                        viewModel.getBookShelfList()

                        ToastUtil.show("操作成功")
                        true
                    }.create().show()
            }
            R.id.bookshelf_iv_nodata->{
                MainEventProxy.postToHomeEvent()
            }
            R.id.bookshelf_cl_today_recommend->{
                val netBookBean=viewModel.todayRecommendBook.value?:return

                val bookBean=BookBean()
                bookBean.id=netBookBean.bookId.toString()
                bookBean.bookName=netBookBean.bookName
                bookBean.thumb=netBookBean.cover
                bookBean.author=netBookBean.author
                bookBean.textCount=netBookBean.words

                BusinessJumpUtil.toBookReader(bookBean)
            }
        }
    }


}